package com.neucloud.da.edgeside.utils;

import cn.hutool.core.util.StrUtil;
import com.neucloud.da.edgeside.model.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.Locale;

@Slf4j
public class FileUtil {

    public static File multifileToFile(MultipartFile file){
        try {
            String fileName = file.getOriginalFilename();
            String[] fileNameContent = fileName.split("\\.");
            File tempFile = File.createTempFile(fileNameContent[0], "." + fileNameContent[1]);
            file.transferTo(tempFile);
            return tempFile;
        } catch (IOException e) {
            throw new BusinessException("MultipartFile转为File异常"+e.getMessage());
        }
    }

    public static File writeToFile(String fileName, String suffix, String context){
        File tempFile = createTempFile(fileName, suffix);
        FileWriter fileWriter = null;
        try {
            fileWriter = new FileWriter(tempFile);
            PrintWriter out = new PrintWriter(fileWriter);
            out.write(context);
            out.println();
            fileWriter.close();
            out.close();
        } catch (IOException e) {
            log.error("字符串写入到文件异常:{}", e.getMessage());
            throw new BusinessException("字符串写入到文件异常:" + e.getMessage());
        }
        return tempFile;
    }


    public static File createTempFile(String fileName, String suffix){
        File tempFile = null;
        try {
            tempFile = File.createTempFile(fileName, suffix);
            return tempFile;
        } catch (IOException e) {
            log.error("创建临时文件异常:{}", e.getMessage());
            throw new BusinessException("创建临时文件异常");
        }
    }

    /**
     * @param fileSize  文件长度
     * @param limitSize 限制大小 单位 M
     * @描述 判断文件大小
     */
    public static boolean checkFileSize(Long fileSize, int limitSize) {
        return checkFileSize(fileSize,limitSize,"M");
    }

    /**
     * @param fileSize  文件长度
     * @param limitSize 限制大小
     * @param limitUnit 限制单位（B,K,M,G）
     * @描述 判断文件大小
     */
    public static boolean checkFileSize(Long fileSize, int limitSize, String limitUnit) {
        double size = 0;
        if ("B".equalsIgnoreCase(limitUnit)) {
            size = (double) fileSize;
        } else if ("K".equalsIgnoreCase(limitUnit)) {
            size = (double) fileSize / 1024;
        } else if ("M".equalsIgnoreCase(limitUnit)) {
            size = (double) fileSize / 1048576;
        } else if ("G".equalsIgnoreCase(limitUnit)) {
            size = (double) fileSize / 1073741824;
        }
        return size > limitSize;
    }

    /**
     * 获取文件的扩展名统一转换为小写
     *
     * @param fileName 文件名称
     * @return 小写扩展名
     */
    public static String getExt(String fileName) {
        if (fileName == null) {
            return null;
        }
        if (fileName.contains(".")) {
            String ext = fileName.substring(fileName.lastIndexOf(".") + 1);
            if (StrUtil.isNotEmpty(ext)) {
                ext = ext.toLowerCase(Locale.ROOT);
            }
            return ext;
        }
        return null;
    }

    /**
     * 获取文件的原始后缀名
     *
     * @param fileName 文件名称
     * @return 原始扩展名
     */
    public static String getOriginExt(String fileName) {
        if (fileName == null) {
            return null;
        }
        if (fileName.contains(".")) {
            return fileName.substring(fileName.lastIndexOf(".") + 1);
        }
        return null;
    }

    public static String getFileName(String fileName) {
        if (fileName == null) {
            return null;
        }
        if (fileName.contains(".")) {
            return fileName.substring(0, fileName.lastIndexOf("."));
        }
        return null;
    }

    /**
     * 根据文件名称 获取bucket 名称，默认为第一层为bucket名称，例如：/dctask/DC20211223012/uuid/filename.xls  对应bucket名称为 dctask
     *
     * @param fileName 文件名称
     * @return MinIo桶名称
     */
    public static String getBucketName(String fileName) {
        if (StrUtil.isEmpty(fileName)) {
            return "";
        }
        if (fileName.indexOf("/") > 0) {
            String[] paths = fileName.split("/");
            if (fileName.startsWith("/")) {
                return paths[1];
            } else {
                return paths[0];
            }
        }
        return fileName;
    }

    /**
     * 根据文件名称获取存储在oss的文件路径，截取掉 bucket名称
     *
     * @param fileName 文件名称
     * @return oss的文件路径
     */
    public static String getMinioFileName(String fileName) {
        if (StrUtil.isEmpty(fileName)) {
            return "";
        }
        String bucketName = getBucketName(fileName);
        if (fileName.startsWith("/")) {
            bucketName = "/" + bucketName;

        }
        return fileName.substring(bucketName.length() + 1);
    }


}
